﻿using System;
using System.Collections.Generic;

using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace Utilities.Common
{   
    public class ProxyBuilder
    {
        /// <summary>
        /// Indica el path al assemble donde estan las clases de negocio.
        /// </summary>
       // public static string BLAssemblyPath { get; set; }

        public static IProxy Build(ClassInfo info, object obj)
        {
            string properties = "";
            foreach (var item in info.Properties)
            {
                properties += "case  \"" + item.Name + "\": return obj." + item.Name + "; ";
            }
#warning hacer variable el namespace
            string source = "using System;using BL.Entities;namespace Utilities.Common{";
            source+="public sealed class "+info.ClassName+"Proxy:IProxy{";
            source+="public object GetValue(string property, object unCastedObj){";
            source += info.ClassName+ " obj=("+info.ClassName+")unCastedObj; switch (property){";
            source += properties;   
            source +="}return null;} public object GetNew(){return new "+info.ClassName+"();}}}";
            CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
            CompilerParameters compilerParameters = new CompilerParameters();          
            compilerParameters.GenerateInMemory = true;           
            compilerParameters.GenerateExecutable = false; 
            compilerParameters.ReferencedAssemblies.Add("system.dll");
            compilerParameters.ReferencedAssemblies.Add(info.GetType().Assembly.Location);
            compilerParameters.ReferencedAssemblies.Add(obj.GetType().Assembly.Location);
#warning fijarse si hay errores antes de retornar el proxy
            CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, source);
            return (IProxy)compilerResults.CompiledAssembly.CreateInstance("Utilities.Common."+info.ClassName+"Proxy");
        }
    }
     
}